package com.example;

import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.hhq.annotation.ViewFun;
import com.hhq.core.Req;
import com.hhq.core.Res;

import java.util.Random;

/**
 * 在这个类编写视图函数
 */
public class Views {

    /**
     *  必须是public  
     * 加上@ViewFun注解指明这是个视图函数，path是要匹配的路径，method是http方法
     * 从req获取请求头和数据
     * 将返回的数据写入res
     *  */
    @ViewFun(path = "/", method = "get")
    public void index(Req req, Res res) {

        Map<String, String> map = new TreeMap<>();
        map.put("name", "value");
        map.put("pwd", "asda");
        String body = JSONObject.toJSONString(map);
        res.headers.put("Content-type", "application/json; charset=utf-8"); // 编码相关
        res.body = body;
    }

    @ViewFun(path="/2", method = "get")
    public void index2(Req req, Res res) {

        Map<String, String> map = new TreeMap<>();
        map.put("name", "Bob John");
        map.put("pwd", "123456");
        String body = JSONObject.toJSONString(map);
        res.headers.put("Content-type", "application/json; charset=utf-8"); // 编码相关
        res.body = body;
    }

    @ViewFun(path="/getRandInt", method = "get")
    public void getRandInt(Req req, Res res) {  
        
        JSONObject jso = new JSONObject();
        jso.put("value", (new Random()).nextInt(99999999)); 
        String body = JSONObject.toJSONString(jso);
        res.headers.put("Content-type", "application/json; charset=utf-8"); // 编码相关
        res.body = body;
    }
}